package indzcraft.loader;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class Database {
	
	private HashMap<Integer,Item> db = new HashMap<Integer,Item>();
	IndzCraftLoader loader;

	public Database(IndzCraftLoader loader) {
		this.loader = loader;
		loadFromStorage();
	}
	
	public void loadFromStorage(){
		File file = new File("./wowhead/");
		if(!file.exists()){
			file.mkdir();
		}
		else if(file.exists()){
			System.out.println("Path /wowhead/ exists");
			File[] files = file.listFiles();
			for(int i = 0;i< files.length;i++){
				if(files[i].isFile()){
					int itemid = Integer.parseInt(files[i].getName().split("\\.")[0]);
					Item item = loader.getItemFromWOWHEAD(itemid);
					if(item != null)
						db.put(item.getId(), item);
				}
			}
		}
		System.out.println("directory wowhead imported");
	}
	
	public void put(int id,Item item){
		db.put(id, item);
	}

	public Item get(int id){
		if(!db.containsKey(id)){
			Item item = loader.getItemFromWOWHEAD(id);
			if(item != null)
				db.put(item.getId(), item);
		}
		//System.out.println("load from db: "+ id);
		return db.get(id);
	}
	
	public ArrayList<Item> findAllWithInventorySlot(Slot slot){
		List<Integer> integers = slot.getInventorySlots();
		//Arrays.sort(integers);
		ArrayList<Item> list = new ArrayList<Item>();
		for(Integer i : db.keySet()){
			int invSlot = db.get(i).getInventorySlot();
			if(integers.contains(invSlot)){
					list.add(db.get(i));
			}
		}
		return list;
	}
}
